package com.apache.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/** 
 * MD5.java Create on Sep 5, 2008 4:54:43 PM 
 * <p> MD5 加密.</p>
 * @version v 0.1
 */
public class MD5Utils {

	public static final int OXFF = 0xff;
	public static final int OX10 = 0x10;

	/**
	 * 默认的构造方法
	 */
	private MD5Utils() {

	}

	/**
	 * Encodes a string.
	 *
	 * @param str     要加密的字符串/String to encode 
	 * @return String 已加密的字符串/Encoded String
	 * @throws NoSuchAlgorithmException java.security.NoSuchAlgorithmException 
	 */
	public static String crypt(String str) throws NoSuchAlgorithmException {
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}

		StringBuffer hexString = new StringBuffer();

		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());
		byte[] hash = md.digest();

		for (byte aHash : hash) {
			if ((OXFF & aHash) < OX10) {
				hexString.append("0").append(Integer.toHexString((OXFF & aHash)));
			} else {
				hexString.append(Integer.toHexString(OXFF & aHash));
			}
		}

		return hexString.toString();
	}

	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] btInput = s.getBytes();
			//获得MD5摘要算法的 MessageDigest 对象 
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			//使用指定的字节更新摘要 
			mdInst.update(btInput);
			//获得密文 
			byte[] md = mdInst.digest();
			//把密文转换成十六进制的字符串形式 
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		String pass = MD5Utils.MD5(MD5Utils.MD5("aieadmin")+"iussoft");
		System.out.println(pass);
	}
}
